const validate = require("validate.js");

const { formatResponse } = require("../utils/tool");
const {
  createArticleDao,
  deleteArticleDao,
  findByPkArticleDao,
  updateArticleDao,
} = require("../dao/articleDao");

const { findByPkBlogTypeDao } = require("../dao/blogTypeDao");

const { ValidationError } = require("../utils/error");

exports.createArticleService = async (data) => {
  validate.validators.blogTypeExits = async function (value) {
    const c = await findByPkBlogTypeDao(value);
    if (c) {
      return;
    }
    return "blogType is not exist";
  };

  const rules = {
    name: {
      presence: { allowEmpty: false },
      length: { minimum: 2, maximum: 50 },
    },
  };

  const result = await validate.async(data, rules);

  if (result) {
    const [key] = Object.keys(result);
    throw new ValidationError(result[key][0]);
  }

  const res = await createArticleDao(data);
  return formatResponse(0, "", res.dataValues);
};

exports.deleteArticleService = async (id) => {
  const res = await deleteArticleDao(id);
  if (!res) throw new ValidationError("Article is not exist");
  return formatResponse(0, "", null);
};

exports.findAllArticleService = async () => {
  return await findAllArticleDao();
};

exports.updateArticleService = async (id, data) => {
  await updateArticleDao(id, data);
  return formatResponse(0, "", null);
};

exports.findByIdArticleService = async (id) => {
  const res = await findByPkArticleDao(id);
  if (res) return formatResponse(0, "", res.dataValues);
  if (!res) throw new ValidationError("Article is not exist");
};
